package com.kuang.demo.typeHandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@MappedTypes(List.class)//javaType
@MappedJdbcTypes(JdbcType.VARCHAR)//数据库
public class String4ListString implements TypeHandler<List<String>> {
    ObjectMapper objectMapper = new ObjectMapper();

    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, List<String> strings, JdbcType jdbcType) throws SQLException {
        String string = objectMapper.writeValueAsString(strings);
        preparedStatement.setString(index,string);
    }

    @SneakyThrows
    @Override
    public List<String> getResult(ResultSet resultSet, String s) throws SQLException {
        String string = resultSet.getString(s);
        List<String> list = stringForList(string);
        return list;
    }
    @SneakyThrows
    @Override
    public List<String> getResult(ResultSet resultSet, int i) throws SQLException {
        String string = resultSet.getString(i);
        List<String> list = stringForList(string);
        return list;
    }

    @SneakyThrows
    @Override
    public List<String> getResult(CallableStatement callableStatement, int i) throws SQLException {
        String string = callableStatement.getString(i);
        List<String> list = stringForList(string);
        return list;
    }

    private List<String> stringForList(String string) throws com.fasterxml.jackson.core.JsonProcessingException {
        return objectMapper.readValue(string, List.class);
    }

}
